﻿using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Net;
using System.Text;


namespace ScrumFactory.Services.Logic.AuthProviders {

    [Export(typeof(IAuthorizationProviderService))]
    public class GoogleAuthorizationProvider : IAuthorizationProviderService {


        private bool IsProviderEnabled {
            get {
                bool setting = true;
                string settingStr = System.Configuration.ConfigurationManager.AppSettings["Enable-GoogleAuthorizationProvider"];
                if (String.IsNullOrEmpty(settingStr))
                    return setting;
                bool.TryParse(settingStr, out setting);

                return setting;
            }
        }

        #region IAuthorizationProviderService Members

        public string ProviderName {
            get {
                return "Google";
            }
        }

        public string GetAuthorizationToken(string user, string password) {
            throw new NotSupportedException();
        }

        public bool PasswordRequired {
            get {
                return true;
            }
        }

        public bool IsNetworkUser {
            get {
                return false;
            }
        }

        private System.Net.IWebProxy GetProxy() {

            return WebRequest.DefaultWebProxy;

            //Microsoft.Win32.RegistryKey internetSettingsKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings");
            //int? proxyEnable = internetSettingsKey.GetValue("ProxyEnable") as int?;
            //string proxyServer = internetSettingsKey.GetValue("ProxyServer") as string;
            //string proxyOverride = internetSettingsKey.GetValue("ProxyOverride") as string;
            //bool byPassLocal = "<local>".Equals(proxyOverride);
            //if (proxyEnable.HasValue && proxyEnable.Value == 1)
            //    return new System.Net.WebProxy(proxyServer, byPassLocal, null, System.Net.CredentialCache.DefaultCredentials);

            //return null;
        }

        public bool ValidadeToken(string token, string user) {

            if(!IsProviderEnabled)
                throw new System.ServiceModel.Web.WebFaultException<string>("Provider not supported", System.Net.HttpStatusCode.NotImplemented);                
          
            // creates the request
            HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create("https://www.google.com/m8/feeds/contacts/default/thin");
            authRequest.Method = "GET";            
            authRequest.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + token);
            authRequest.Proxy = GetProxy();
            
            try {
                
                // makes the request            
                HttpWebResponse response = (HttpWebResponse)authRequest.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK) {                    
                    return true;
                }

                Stream respStream = response.GetResponseStream();
                string resp = string.Empty;
                if (respStream != null) {
                    StreamReader responseReader = new StreamReader(response.GetResponseStream());
                    resp = responseReader.ReadToEnd();
                }
                ScrumFactory.Services.Logic.Helper.Log.LogMessage("Google login failed: " + response.StatusCode + "\n" + resp);
            
            
            } catch (Exception e) {
                ScrumFactory.Services.Logic.Helper.Log.LogError(e);
                throw new System.ServiceModel.Web.WebFaultException<string>("Token not valid: " + e.Message, System.Net.HttpStatusCode.BadRequest);                
            }

            return false;
        }

        #endregion
    }
}
